# Author: 空间栈
# Gitee: https://gitee.com/shujianyang/gras-data-processing

import argparse
from pathlib import Path
import xml.etree.ElementTree as ET

ap = argparse.ArgumentParser()
ap.add_argument('-i', '--inputdir', required=True,
                help='Input folder where data files are stored.')
ap.add_argument('-t', '--template', required=True,
                help='Label file template.')
args = vars(ap.parse_args())

dir_path = args['inputdir']
template = args['template']
label_extension = Path(template).suffix
data_file_extension = label_extension[:-1]

#根据模板标签文件后缀筛选数据文件
#Filter data files based on template extension.
data_files = Path(dir_path).glob('*' + data_file_extension)

ET.register_namespace('', "http://pds.nasa.gov/pds4/pds/v1")
tree = ET.parse(template)
root = tree.getroot()

for data_file in data_files:
    #如果标签文件已存在则跳过
    #Skip if a valid label file already exists.
    standard_label_path = f"{str(data_file)}L"
    if Path(standard_label_path).exists():
        print('-----' + standard_label_path + ' exists. Skipped.')
        continue

    data_size = data_file.stat().st_size

    #文件尺寸检查
    #File size check.
    size_unmatched = False
    for file_size in root.iter('{http://pds.nasa.gov/pds4/pds/v1}file_size'):
        if data_size != int(file_size.text):
            size_unmatched = True
            break
    if size_unmatched:
        continue

    #替换模板标签文件中的文件名
    #Replace the file name within the template.
    for file_name in root.iter('{http://pds.nasa.gov/pds4/pds/v1}file_name'):
        file_name.text = data_file.name

    #生成临时标签文件，附带-temp后缀
    #Generated a temporary label file with "-temp" suffix.
    new_label_path = str(data_file.with_name(f"{data_file.stem}-temp{data_file.suffix}L"))
    tree.write(new_label_path,
               xml_declaration=True,encoding='utf-8',
               method="xml")

    print('---' + new_label_path + ' generated.')